﻿using System.Net.Sockets;
using MoonFramework.Tool;
using Serilog;

namespace MoonFramework.Net
{
	/// <summary>
	/// 网络服务
	/// </summary>
	public class NetService
	{
		private readonly TcpServer listener;

		public NetService(int port)
		{
			listener = new TcpServer("0.0.0.0", port);
			listener.SocketConnected += OnClientConnected;
		}

		public void Start(int number = 8)
		{
			listener.Start();	//开始监听消息
			MessageRouter.Instance.Start(number);	//默认分配八个线程处理消息
		}

		private void OnClientConnected(object? sender, Socket socket)
		{
			var connection = new BaseConnection();
			connection.DataReceived += OnDataReceived;
			connection.DisConnected += OnDisConnected;
			connection.Start(socket);
		}


		private async void OnDataReceived(BaseConnection sender,byte[] data)
		{
			Proto.Package package = ProtoTool.Deserialize<Proto.Package>(data);
			MessageRouter.Instance.SendMessage(sender, package);
		}

		private void OnDisConnected(BaseConnection sender)
		{
            Log.Information("连接断开");
        }
	}
}